package com.example.socialmediaplatform.controller;

import com.example.socialmediaplatform.model.Notification;
import com.example.socialmediaplatform.model.NotificationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/notification")
@CrossOrigin(origins = "*")
public class NotificationController {
    
    @Autowired
    private NotificationRepository notificationRepository;
    
    @GetMapping
    public ResponseEntity<List<Notification>> getNotifications(Authentication authentication) {
        String username = authentication.getName();
        List<Notification> notifications = notificationRepository.findByToUserOrderByCreatedAtDesc(username);
        return ResponseEntity.ok(notifications);
    }
    
    @PostMapping("/{id}/read")
    public ResponseEntity<?> markAsRead(@PathVariable Long id, Authentication authentication) {
        String username = authentication.getName();
        Notification notification = notificationRepository.findByIdAndToUser(id, username);
        if (notification != null) {
            notification.setReaded(true);
            notificationRepository.save(notification);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }
    
    @PostMapping
    public ResponseEntity<Notification> createNotification(@RequestBody Notification notification) {
        notification.setCreatedAt(new Date());
        notification.setReaded(false);
        Notification saved = notificationRepository.save(notification);
        return ResponseEntity.ok(saved);
    }
} 
